"""
游戏UI模块，处理游戏的所有渲染功能。
"""
from typing import List, Tuple, Optional, Dict

import pygame

from tetris.constants import (
    BLOCK_SIZE, BOARD_WIDTH, BOARD_HEIGHT, 
    BLACK, WHITE, GREY, RED, GREEN, BLUE,
    SCREEN_WIDTH, SCREEN_HEIGHT
)
from tetris.player import Player
from tetris.tetromino import Tetromino


class UI:
    """游戏UI类，处理所有绘制操作"""
    
    def __init__(self, screen: pygame.Surface):
        """
        初始化UI
        
        Args:
            screen: pygame屏幕对象
        """
        self.screen = screen
        
        # 尝试使用系统中支持中文的字体
        try:
            # 尝试使用微软雅黑或其他中文字体
            self.font_small = pygame.font.SysFont('microsoftyahei', 18)
            self.font_medium = pygame.font.SysFont('microsoftyahei', 24)
            self.font_large = pygame.font.SysFont('microsoftyahei', 36)
        except:
            # 如果找不到中文字体，退回到默认字体
            default_font = pygame.font.get_default_font()
            self.font_small = pygame.font.Font(default_font, 18)
            self.font_medium = pygame.font.Font(default_font, 24) 
            self.font_large = pygame.font.Font(default_font, 36)
        
        # 计算游戏板位置，确保有足够的空间显示周边信息
        board_pixel_width = BOARD_WIDTH * BLOCK_SIZE
        board_pixel_height = BOARD_HEIGHT * BLOCK_SIZE
        
        # 两个游戏板之间的间距增加
        spacing = 100
        
        # 给侧边预留更多空间
        self.p1_x = 200
        self.p1_y = (SCREEN_HEIGHT - board_pixel_height) // 2
        
        # 计算玩家2游戏板位置
        self.p2_x = self.p1_x + board_pixel_width + spacing
        self.p2_y = self.p1_y
    
    def draw_background(self) -> None:
        """绘制游戏背景"""
        self.screen.fill(BLACK)
    
    def draw_board(self, board: List[List[Optional[Tuple[int, int, int]]]], x: int, y: int) -> None:
        """绘制游戏板"""
        # 绘制边框
        pygame.draw.rect(
            self.screen, 
            WHITE, 
            (x - 2, y - 2, BOARD_WIDTH * BLOCK_SIZE + 4, BOARD_HEIGHT * BLOCK_SIZE + 4),
            2
        )
        
        # 先完全清除游戏板区域，确保没有任何残留
        pygame.draw.rect(
            self.screen,
            BLACK,
            (x, y, BOARD_WIDTH * BLOCK_SIZE, BOARD_HEIGHT * BLOCK_SIZE)
        )
        
        # 获取当前游戏时间，用于确定是否在游戏初始阶段
        game_start_phase = False
        try:
            # 尝试获取游戏时间，如果是菜单状态可能会失败
            from tetris.game import Game
            current_game = Game.current_instance
            if current_game and hasattr(current_game, 'players') and current_game.players:
                game_time = max(player.game_time for player in current_game.players)
                game_start_phase = game_time < 1.0  # 只在游戏开始的第一秒清除T方块
        except:
            game_start_phase = False
        
        # 绘制网格和方块
        for row in range(BOARD_HEIGHT):
            for col in range(BOARD_WIDTH):
                cell_x = x + col * BLOCK_SIZE
                cell_y = y + row * BLOCK_SIZE
                
                # 绘制网格线
                pygame.draw.rect(
                    self.screen,
                    GREY,
                    (cell_x, cell_y, BLOCK_SIZE, BLOCK_SIZE),
                    1
                )
                
                # 检查是不是那个顽固的粉色方块
                cell_color = board[row][col]
                if cell_color is not None:
                    # 特殊条件：底部区域的粉色方块（T形）跳过绘制
                    # if cell_color == (255, 0, 255) and row > BOARD_HEIGHT // 2:
                    #     # 跳过绘制，强制清除
                    #     board[row][col] = None
                    #     continue
                    
                    # 验证颜色值是否有效
                    if isinstance(cell_color, tuple) and len(cell_color) == 3:
                        pygame.draw.rect(
                            self.screen,
                            cell_color,
                            (cell_x + 1, cell_y + 1, BLOCK_SIZE - 2, BLOCK_SIZE - 2)
                        )
                    else:
                        # 如果颜色值无效，打印警告并使用默认颜色
                        print(f"警告: 无效的颜色值 {cell_color} 在 ({col}, {row})")
                        # 使用灰色替代无效颜色
                        pygame.draw.rect(
                            self.screen,
                            GREY,
                            (cell_x + 1, cell_y + 1, BLOCK_SIZE - 2, BLOCK_SIZE - 2)
                        )
    
    def draw_tetromino(self, tetromino: Tetromino, board_x: int, board_y: int) -> None:
        """
        绘制方块
        
        Args:
            tetromino: 要绘制的方块
            board_x: 游戏板左上角的x坐标
            board_y: 游戏板左上角的y坐标
        """
        # 限制调试输出，只打印玩家1的方块变化
        # print(f"Drawing tetromino at {tetromino.x}, {tetromino.y}, type: {tetromino.shape_type}")
        
        for x, y in tetromino.get_coords():
            # 只绘制在游戏板内的部分
            if 0 <= y < BOARD_HEIGHT and 0 <= x < BOARD_WIDTH:
                cell_x = board_x + x * BLOCK_SIZE
                cell_y = board_y + y * BLOCK_SIZE
                
                pygame.draw.rect(
                    self.screen,
                    tetromino.color,
                    (cell_x + 1, cell_y + 1, BLOCK_SIZE - 2, BLOCK_SIZE - 2)
                )
    
    def draw_next_tetromino(self, tetromino: Tetromino, x: int, y: int) -> None:
        """
        绘制下一个方块提示
        
        Args:
            tetromino: 下一个方块
            x: 绘制区域左上角的x坐标
            y: 绘制区域左上角的y坐标
        """
        # 绘制边框和标签
        pygame.draw.rect(
            self.screen,
            WHITE,
            (x, y, 6 * BLOCK_SIZE, 6 * BLOCK_SIZE),
            2
        )
        
        next_text = self.font_small.render("下一个:", True, WHITE)
        self.screen.blit(next_text, (x + 10, y + 10))
        
        # 获取方块坐标并居中显示
        shape_width = max(coord[0] for coord in tetromino.shape[0]) + 1
        shape_height = max(coord[1] for coord in tetromino.shape[0]) + 1
        
        for dx, dy in tetromino.shape[0]:
            cell_x = x + (dx + (6 - shape_width) // 2) * BLOCK_SIZE
            cell_y = y + (dy + (6 - shape_height) // 2) * BLOCK_SIZE + BLOCK_SIZE
            
            pygame.draw.rect(
                self.screen,
                tetromino.color,
                (cell_x, cell_y, BLOCK_SIZE - 2, BLOCK_SIZE - 2)
            )
    
    def draw_score(self, player: 'Player', x: int, y: int) -> None:
        """绘制玩家分数信息"""
        # 调整为更紧凑的样式
        score_info = [
            f"玩家 {player.player_id}",
            f"分数: {player.board.score}",
            f"等级: {player.board.level}",
            f"消除行数: {player.board.lines_cleared}"
        ]
        
        for i, text in enumerate(score_info):
            score_text = self.font_small.render(text, True, WHITE)
            self.screen.blit(score_text, (x, y + i * 22))
    
    def draw_controls(self, player: 'Player', x: int, y: int) -> None:
        """
        绘制玩家控制说明
        
        Args:
            player: 玩家对象
            x: 绘制位置x坐标
            y: 绘制位置y坐标
        """
        # 调整字体大小，让控制信息更紧凑
        controls_font = self.font_small
        
        # 更精简的控制说明
        controls = [
            f"左移: {player.controls['LEFT']}",
            f"右移: {player.controls['RIGHT']}",
            f"下移: {player.controls['DOWN']}",
            f"旋转: {player.controls['ROTATE']}",
            f"直接下落: {player.controls['DROP']}"
        ]
        
        for i, text in enumerate(controls):
            # 行间距调小
            control_text = controls_font.render(text, True, WHITE)
            self.screen.blit(control_text, (x, y + i * 20))  # 行间距调整为20
    
    def draw_game_over(self, player_id: int) -> None:
        """
        绘制游戏结束画面
        
        Args:
            player_id: 输掉游戏的玩家ID
        """
        overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 180))  # 半透明黑色
        self.screen.blit(overlay, (0, 0))
        
        winner_id = 2 if player_id == 1 else 1
        game_over_text = self.font_large.render(f"游戏结束! 玩家{winner_id}获胜!", True, WHITE)
        restart_text = self.font_medium.render("按R键重新开始", True, WHITE)
        quit_text = self.font_medium.render("按ESC键退出", True, WHITE)
        
        game_over_rect = game_over_text.get_rect(center=(SCREEN_WIDTH//2, SCREEN_HEIGHT//2 - 50))
        restart_rect = restart_text.get_rect(center=(SCREEN_WIDTH//2, SCREEN_HEIGHT//2 + 10))
        quit_rect = quit_text.get_rect(center=(SCREEN_WIDTH//2, SCREEN_HEIGHT//2 + 50))
        
        self.screen.blit(game_over_text, game_over_rect)
        self.screen.blit(restart_text, restart_rect)
        self.screen.blit(quit_text, quit_rect)
    
    def draw_pause_screen(self) -> None:
        """绘制暂停画面"""
        overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 180))  # 半透明黑色
        self.screen.blit(overlay, (0, 0))
        
        pause_text = self.font_large.render("游戏暂停", True, WHITE)
        continue_text = self.font_medium.render("按P键继续", True, WHITE)
        
        pause_rect = pause_text.get_rect(center=(SCREEN_WIDTH//2, SCREEN_HEIGHT//2 - 30))
        continue_rect = continue_text.get_rect(center=(SCREEN_WIDTH//2, SCREEN_HEIGHT//2 + 30))
        
        self.screen.blit(pause_text, pause_rect)
        self.screen.blit(continue_text, continue_rect)
    
    def draw_title_screen(self) -> None:
        """绘制标题画面"""
        self.screen.fill(BLACK)
        
        title_text = self.font_large.render("双人俄罗斯方块", True, WHITE)
        start_text = self.font_medium.render("按空格键开始游戏", True, WHITE)
        
        title_rect = title_text.get_rect(center=(SCREEN_WIDTH//2, SCREEN_HEIGHT//2 - 50))
        start_rect = start_text.get_rect(center=(SCREEN_WIDTH//2, SCREEN_HEIGHT//2 + 50))
        
        self.screen.blit(title_text, title_rect)
        self.screen.blit(start_text, start_rect)
    
    def clear_cache(self) -> None:
        """清除任何可能的缓存"""
        # 在这里添加任何需要清除的缓存
        # 例如，强制重绘整个屏幕
        self.screen.fill(BLACK)
        pygame.display.flip()
        print("UI缓存已清除")
    
    def draw_board_background(self, x: int, y: int) -> None:
        """绘制空的游戏板背景"""
        # 填充游戏板区域为黑色
        pygame.draw.rect(
            self.screen,
            BLACK,
            (x, y, BOARD_WIDTH * BLOCK_SIZE, BOARD_HEIGHT * BLOCK_SIZE)
        )
        
        # 绘制边框
        pygame.draw.rect(
            self.screen, 
            WHITE, 
            (x - 2, y - 2, BOARD_WIDTH * BLOCK_SIZE + 4, BOARD_HEIGHT * BLOCK_SIZE + 4),
            2
        ) 